import vuex from 'vuex';
import Vue from 'vue';
import router from '../router';
Vue.use(vuex);
import http from '../utils/http';

const store = new vuex.Store({
    state: {
        token: null,
        userInfo: null,
        permission: []
    },
    mutations: {
        login(state,payload) {
            state.userInfo = payload.userInfo;
            state.token = payload.token;
            localStorage.setItem('token', payload.token); // 保存到 localStorage
            localStorage.setItem('userInfo', JSON.stringify(payload.userInfo)); // 保存到 localStorage
            // console.log("登录成功，保存到localStorage的token是：",payload.token);
            // console.log("登录成功，保存到localStorage的userInfo是：",payload.userInfo);
            // console.log("登录成功，保存到store的token是：",state.token);
            // console.log("登录成功，保存到store的userInfo是：",state.userInfo);

          },
        logout(state) {
            state.userInfo = null;
            state.token = null;
            localStorage.removeItem('token'); // 清除本地存储
            localStorage.removeItem('userInfo'); // 清除本地存储
            router.push('/login');
        },
        initTokenSync(state,payload){
            state.token = payload.token;
            state.userInfo = JSON.parse(payload.userInfo);
        },
        setPermission(state,payload) {
            state.permission = payload.data;
            // console.log("登录成功，保存到store的permission是：",state.permission);
        }
    },
    actions: {
        async initToken(context){
            const token = localStorage.getItem('token');
            const userInfo = localStorage.getItem('userInfo');
            // console.log("初始化获取的本地token是：",token);
            // console.log("初始化获取的本地userInfo是：",userInfo);
            if(!token){
            context.commit('logout');
            }else{
              const result = await http.get('/verifyTokenInit',{
                headers:{
                  Authorization:token
                }
              });
              if(result.code !== 1){
               context.commit('logout');
              }else{
                context.commit('initTokenSync',{
                  token:token,
                  userInfo:userInfo
                });
                return token;
              }
            }
          }
    }
})

export default store;